package com.bidevalution.support.util;

import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * @author huyiqi
 * @date 2020/5/6
 */
public class UrlUtil {

    private static final String URL_FORMAT = "%s/%s";
    private static final String SLASH = "/";

    /**
     * 将数组内容用斜杠拼接
     * @param urls 需要拼接的url们
     * @return 返回拼接好的url
     */
    public static String spliceUrl(String... urls) {
        String result = "";
        if(urls.length > 0) {
            List<String> urlList = Arrays.asList(urls);
            Iterator<String> it = urlList.iterator();
            result = it.next();
            while(it.hasNext()) {
                String left = removeRightSlash(result);
                String right = removeLeftSlash(it.next());
                result = String.format(URL_FORMAT, left, right);
            }
        }
        return result;
    }

    /**
     * 去掉字符串左边所有的斜杠
     * @param str 字符串
     * @return 去掉左边斜杠的字符串
     */
    private static String removeLeftSlash(String str) {
        if(StringUtils.isNotBlank(str)) {
            while (str.indexOf(SLASH) == 0) {
                str = str.substring(1, str.length());
            }
        }
        return str;
    }

    /**
     * 去掉字符串右边所有的斜杠
     * @param str 字符串
     * @return 去掉右边斜杠的字符串
     */
    private static String removeRightSlash(String str) {
        if(StringUtils.isNotBlank(str)) {
            int lastCharIndex = str.length() - 1;
            while (str.lastIndexOf(SLASH) == lastCharIndex) {
                str = str.substring(0, lastCharIndex);
                lastCharIndex = str.length() - 1;
            }
        }
        return str;
    }
}
